import React, { useState, useEffect } from 'react';
import { getIncomeRecords, getTotalIncome, getUnpaidBills, payBill } from '../services/api';
import { Bar } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend } from 'chart.js';
import { CurrencyYenIcon, CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/outline';

// 注册Chart.js组件
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);

const Income = () => {
  const [incomeRecords, setIncomeRecords] = useState([]);
  const [unpaidBills, setUnpaidBills] = useState([]);
  const [totalIncome, setTotalIncome] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [paymentLoading, setPaymentLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');

  useEffect(() => {
    // 首次加载
    const fetchData = async (showLoading = true) => {
      try {
        if (showLoading) {
          setLoading(true);
        }
        const [recordsResponse, totalResponse, unpaidResponse] = await Promise.all([
          getIncomeRecords(),
          getTotalIncome(),
          getUnpaidBills()
        ]);
        
        setIncomeRecords(recordsResponse.data);
        setTotalIncome(totalResponse.data.total);
        setUnpaidBills(unpaidResponse.data);
        if (showLoading) {
          setError(null);
        }
      } catch (err) {
        console.error('获取收入数据失败:', err);
        if (showLoading) {
          setError('获取收入数据失败，请稍后重试');
        }
      } finally {
        if (showLoading) {
          setLoading(false);
        }
      }
    };

    // 首次加载显示loading
    fetchData(true);
    
    // 设置重要数据的定时刷新（未支付账单需要实时性）
    const importantDataIntervalId = setInterval(async () => {
      try {
        // 获取未支付账单和总收入数据（重要数据）
        const [totalResponse, unpaidResponse] = await Promise.all([
          getTotalIncome(),
          getUnpaidBills()
        ]);
        setTotalIncome(totalResponse.data.total);
        setUnpaidBills(unpaidResponse.data);
      } catch (err) {
        console.error('更新重要收入数据失败:', err);
      }
    }, 1000); // 每1秒刷新重要数据
    
    // 设置不重要数据的定时刷新（图表和历史收入）
    const lessImportantDataIntervalId = setInterval(async () => {
      try {
        // 获取收入记录数据（用于图表和历史记录，不那么重要）
        const recordsResponse = await getIncomeRecords();
        setIncomeRecords(recordsResponse.data);
      } catch (err) {
        console.error('更新收入记录数据失败:', err);
      }
    }, 5000); // 每5秒刷新次要数据
    
    return () => {
      clearInterval(importantDataIntervalId);
      clearInterval(lessImportantDataIntervalId);
    };
  }, []);

  // 处理账单支付
  const handlePayBill = async (billId) => {
    try {
      setPaymentLoading(true);
      await payBill(billId);
      
      // 更新未支付账单列表
      const updatedUnpaid = unpaidBills.filter(bill => bill.id !== billId);
      setUnpaidBills(updatedUnpaid);
      
      // 刷新收入记录
      const recordsResponse = await getIncomeRecords();
      setIncomeRecords(recordsResponse.data);
      
      // 刷新总收入
      const totalResponse = await getTotalIncome();
      setTotalIncome(totalResponse.data.total);
      
      // 显示成功消息
      setSuccessMessage('账单支付成功');
      setTimeout(() => setSuccessMessage(''), 3000); // 3秒后清除消息
      
    } catch (err) {
      console.error('支付账单失败:', err);
      setError('支付账单失败，请稍后重试');
      setTimeout(() => setError(null), 3000); // 3秒后清除错误
    } finally {
      setPaymentLoading(false);
    }
  };

  // 为图表准备数据
  const prepareChartData = () => {
    // 按日期分组
    const groupedByDate = incomeRecords.reduce((acc, record) => {
      // 提取日期
      const date = new Date(record.end_time).toLocaleDateString();
      
      if (!acc[date]) {
        acc[date] = 0;
      }
      
      acc[date] += record.amount;
      return acc;
    }, {});
    
    // 转换为图表数据
    const labels = Object.keys(groupedByDate).slice(-7); // 最近7天
    const data = labels.map(date => groupedByDate[date] || 0);
    
    return {
      labels,
      datasets: [
        {
          label: '日收入 (元)',
          data,
          backgroundColor: 'rgba(54, 162, 235, 0.5)',
          borderColor: 'rgb(54, 162, 235)',
          borderWidth: 1,
        },
      ],
    };
  };

  // 图表配置
  const chartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top',
      },
      title: {
        display: true,
        text: '最近收入趋势',
      },
    },
    scales: {
      y: {
        beginAtZero: true,
        title: {
          display: true,
          text: '金额 (元)'
        }
      }
    }
  };

  // 格式化时间差为小时和分钟
  const formatDuration = (startTime, endTime) => {
    const start = new Date(startTime);
    const end = new Date(endTime);
    const durationMs = end - start;
    const hours = Math.floor(durationMs / (1000 * 60 * 60));
    const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));
    
    return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
          <p>{error}</p>
        </div>
      </div>
    );
  }

  const chartData = prepareChartData();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">收入管理</h1>
      </div>
      
      {successMessage && (
        <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded flex items-center">
          <CheckCircleIcon className="w-5 h-5 mr-2" />
          <p>{successMessage}</p>
        </div>
      )}
      
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="flex items-center mb-6">
          <div className="rounded-full bg-yellow-500 p-3 mr-4">
            <CurrencyYenIcon className="w-6 h-6 text-white" />
          </div>
          <div>
            <h3 className="text-gray-500 text-sm font-medium">总收入</h3>
            <p className="text-3xl font-bold text-gray-800">{totalIncome.toFixed(2)} 元</p>
          </div>
          <div className="ml-auto">
            <div className="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-sm">
              未支付账单: {unpaidBills.length} 笔
            </div>
          </div>
        </div>
        
        <div className="h-80">
          <Bar data={chartData} options={chartOptions} />
        </div>
      </div>
      
      {/* 双栏布局：未支付账单和收入记录 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 未支付账单表格 */}
        <div className="bg-white rounded-lg shadow-md">
          <div className="p-4 border-b flex justify-between items-center">
            <h2 className="text-lg font-semibold text-gray-800">未支付账单</h2>
            {unpaidBills.length > 0 && (
              <div className="flex items-center text-sm text-red-600">
                <ExclamationCircleIcon className="w-5 h-5 mr-1" />
                共 {unpaidBills.length} 笔
              </div>
            )}
          </div>
          
          <div className="overflow-x-auto" style={{maxHeight: '500px'}}>
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50 sticky top-0">
                <tr>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车牌号
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车位
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    金额
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    停车时长
                  </th>
                  <th className="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {unpaidBills.map((bill) => (
                  <tr key={bill.id} className="bg-red-50 hover:bg-red-100">
                    <td className="px-3 py-2 whitespace-nowrap text-sm font-medium text-gray-900">
                      {bill.plate_number}
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-500">
                      {bill.spot_number || "-"}
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-sm font-bold text-red-600">
                      {bill.amount.toFixed(2)}元
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-500">
                      {formatDuration(bill.entry_time, bill.exit_time)}
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-center">
                      <button
                        onClick={() => handlePayBill(bill.id)}
                        disabled={paymentLoading}
                        className="bg-blue-500 hover:bg-blue-600 text-white py-1 px-2 rounded text-xs focus:outline-none focus:ring-2 focus:ring-blue-300 disabled:opacity-50"
                      >
                        {paymentLoading ? '处理中...' : '标记已支付'}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            
            {unpaidBills.length === 0 && (
              <div className="flex flex-col items-center justify-center py-8 bg-gray-50">
                <CheckCircleIcon className="w-8 h-8 text-green-500 mb-2" />
                <p className="text-gray-500">没有未支付的账单</p>
              </div>
            )}
          </div>
        </div>
        
        {/* 收入记录表格 */}
        <div className="bg-white rounded-lg shadow-md">
          <h2 className="text-lg font-semibold text-gray-800 p-4 border-b">收入记录</h2>
          
          <div className="overflow-x-auto" style={{maxHeight: '500px'}}>
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50 sticky top-0">
                <tr>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    车牌号
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    金额
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    停车时间
                  </th>
                  <th className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {incomeRecords.map((record) => (
                  <tr key={record.id} className="hover:bg-gray-50">
                    <td className="px-3 py-2 whitespace-nowrap text-sm font-medium text-gray-900">
                      {record.plate_number}
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-900 font-medium">
                      {record.amount.toFixed(2)}元
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-sm text-gray-500">
                      {formatDuration(record.start_time, record.end_time)}
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap">
                      {record.paid ? (
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                          已支付
                        </span>
                      ) : (
                        <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
                          未支付
                        </span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            
            {incomeRecords.length === 0 && (
              <p className="text-gray-500 text-center py-8">暂无收入记录</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Income; 